package com.howtodoinjava.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

import com.howtodoinjava.common.FileUploadForm;

@Controller
public class UploadController {

	@RequestMapping(value = "/savefiles", method = RequestMethod.POST)
	public void uploadFile(
			@ModelAttribute("uploadForm") FileUploadForm uploadForm, Model map,
			HttpServletRequest request, HttpServletResponse response)
			throws IllegalStateException, IOException {

		String saveDirectory = request.getSession().getServletContext()
				.getRealPath("/") + "/WEB-INF/upload/";
		System.out.println("Save DIRECTORY PATH ============================");
		System.out.println(saveDirectory);

		List<MultipartFile> crunchifyFiles = uploadForm.getFiles();
		List<String> fileNames = new ArrayList<String>();

		if (null != crunchifyFiles && crunchifyFiles.size() > 0) {
			for (MultipartFile multipartFile : crunchifyFiles) {

				String fileName = multipartFile.getOriginalFilename();
				if (!"".equalsIgnoreCase(fileName)) {
					// Handle file content - multipartFile.getInputStream()
					multipartFile
							.transferTo(new File(saveDirectory + fileName));
					fileNames.add(fileName);
					
				}
			}
		}

	}

}
